import { Button, Select } from 'antd'
import React, { useRef, useState } from 'react'
import ProTable from '@ant-design/pro-table'
import { PlusOutlined } from '@ant-design/icons'
import { PageContainer } from '@ant-design/pro-layout'
import { getPermissionList } from '@/services/permission'
import Create from '@/pages/Configuration/Permission/components/Create'
import Edit from '@/pages/Configuration/Permission/components/Edit'
import GetTime from '@/components/GetTime'

const Index = () => {
  // 权限层级数据
  const [permission, setPermission] = useState([]);
  // 修改权限id
  const [permissionId, setPermissionId] = useState(undefined);
  // 权限select层级数据
  const [res, setRes] = useState([]);
  // 是否显示添加模态框
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 是否显示修改模态框
  const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false)
  // 是否需要插入顶级权限
  const [insert, setInsert] = useState(true)

  const { Option } = Select
  // 表格的ref，便于自定义操作表格
  const actionRef = useRef()

  const columns = [
    {
      title: '名称',
      dataIndex: 'cn_name',
      width: '60%',
    },
    {
      title: '路由名称',
      dataIndex: 'name',
      width: '30%',
    },
    {
      title: '操作',
      hideInSearch: true,
      render: (_, record) =>
        <Button onClick={() => {
          isShowModalEdit(true, record.id)
        }} type="primary" size={'small'}>编辑</Button>,
      width: '10%',
    },
  ]

  /**
   * 控制模态框显示和隐藏
   */
  const isShowModal = (show) => {
    if (insert) {
      res.unshift({ id: 0, cn_name: '顶级权限', children: [] })
      setInsert(false)
    }
    setIsModalVisible(show)
  }

  /**
   * 控制模态框显示和隐藏
   */
  const isShowModalEdit = (show, editId) => {
    if (insert) {
      res.unshift({ id: 0, cn_name: '顶级权限', children: [] })
      setInsert(false)
    }
    setPermissionId(editId)
    setIsModalVisibleEdit(show)
  }

  /**
   * 获取权限列表
   * @returns {Promise<{data}>}
   */
  const getData = async () => {
    const response = await getPermissionList()
    setPermission(response.data)
    setRes(response.data)
    return {
      data: response.data
    }
  }

  /**
   * 更改数据格式 使数据正确显示
   * @type {{children: *, title: string|string|*, value: *, key: *}[]}
   */
  const treeData =
    res.map((item) => {
      return {
        key: item.id,
        value: item.id,
        title: item.cn_name,
        children: item.children.map((item) => {
          return {
            key: item.id,
            value: item.id,
            title: '---' + item.cn_name,
          }
        })
      }
    })

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async () => getData()}
        rowKey="id"
        search={false}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              }
            }
            return values
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="权限列表"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined/>} type="primary" onClick={() => isShowModal(true)}>
            新建
          </Button>,
        ]}
      />
      <Create
        isModalVisible={isModalVisible}
        isShowModal={isShowModal}
        treeData={treeData}
        actionRef={actionRef}
      />
      {
        !isModalVisibleEdit ? '' :
          <Edit
            isModalVisible={isModalVisibleEdit}
            isShowModal={isShowModalEdit}
            treeData={treeData}
            actionRef={actionRef}
            permissionId={permissionId}
          />
      }
    </PageContainer>
  )
}

export default Index
